<template>
  <div class="source" v-loading="pageLoading" element-loading-text="loading">
    <div class="newPageTitle">
      <span class="backIcon" @click="goBack"><i class="el-icon-back"></i></span>
      <h1 style="display: inline-block; margin-left: 10px">
        {{ isAdd ? '添加' : '修改' }}类目II
      </h1>
    </div>
    <el-form :model="datas" :rules="rules" ref="dataForm" label-width="130px">
      <el-row>
        <el-col :span="16" :offset="3">
          <el-form-item label="类目I名称:">
            <el-input v-model="datas.parentName" disabled placeholder=""></el-input>
          </el-form-item>
        </el-col>
        <el-col :span="16" :offset="3">
          <el-form-item label="类目II名称:" prop="categoryName">
            <el-input v-model.trim="datas.categoryName" @input="datas.categoryName=datas.categoryName.replace(/[^\a-\z\A-\Z0-9\u4E00-\u9FA5]/g,'')" placeholder="" maxlength="10" show-word-limit></el-input>
          </el-form-item>
        </el-col>
        <el-col :span="16" :offset="3">
          <el-form-item label="类目图标:">
            <el-upload
              :class="{hideUpload:isUpload}"
              :action="uploadUrl"
              :headers="myHeaders"
              :data="uploadData"
              :file-list="fileList"
              :on-success="onSuccess"
              :on-error="onError"
              :limit="1"
              :on-change="onChange"
              list-type="picture-card"
              :on-remove="handleRemove">
              <i class="el-icon-plus"></i>
            </el-upload>
          </el-form-item>
        </el-col>
      </el-row>
    </el-form>
    <div class="footer">
      <div class="footer-btn">
        <el-button @click="goBack" class="white-btn">取消</el-button>
        <el-button
          @click="onCheck"
          class="search-btn"
          :loading="submitting"
          :disabled="!isUpdate"
          >保存</el-button
        >
      </div>
    </div>
  </div>
</template>

<script>
import Vue from 'vue'
import { ACCESS_TOKEN } from '@/config/variableInit'
import { categoryDetail, categoryUpdate } from '@/api/category'
import { setRouterParams, getRouterParams } from '@/utils/auth'
export default {
  name: 'twoCategory',
  data () {
    return {
      datas: {
        id: '',
        categoryName: '',
        parentId: '',
        categoryLevel: 2,
        path: ''
      },
      fileList: [],
      rules: {
        categoryName: [{ required: true, message: '名称不能为空', trigger: 'blur' }]
      },
      uploadUrl: process.env.VUE_APP_BASE_URL + '/admin/upload/uploadFile',
      myHeaders: { Authorization: Vue.ls.get(ACCESS_TOKEN) },
      uploadData: { fileFlag: 'CATEGORY' },
      isAdd: true,
      level: '',
      id: '',
      isUpdate: '',
      isUpload: false,
      submitting: false,
      pageLoading: false
    }
  },
  watch: {
    datas: {
      handler () {
        this.isUpdate = true
      },
      deep: true
    }
  },
  mounted () {
    let params = {}
    if (Number(this.$route.params.level) >= 0) {
      params = this.$route.params
      setRouterParams(this.$route)
    } else {
      params = getRouterParams(this.$route)
    }
    this.level = params.level
    if (params.id) {
      this.isAdd = false
      this.datas.id = params.id
      this.getDetail()
    }
    if (Number(params.parentId) >= 0) {
      this.isAdd = true
      this.datas.parentId = params.parentId
      this.getParent(params.parentId)
    }
    this.$nextTick(() => {
      this.isUpdate = false
    })
  },
  methods: {
    getParent (id) {
      this.pageLoading = true
      categoryDetail(id).then(res => {
        if (res) {
          if (Number(res.code) === 1) {
            this.datas.parentName = res.obj.categoryName
            this.$nextTick(() => {
              this.isUpdate = false
            })
          } else {
            this.$alert(this.$t(res.code))
          }
          this.pageLoading = false
        }
      }).catch(() => {
        this.pageLoading = false
      })
    },
    // 上传
    onSuccess (res) {
      this.datas.path = res.obj.path
    },
    onError () {
      this.$alert('上传失败，请稍后再试')
    },
    onChange (file, fileList) {
      if (fileList.length !== 0) {
        this.isUpload = true
      } else {
        this.isUpload = false
      }
    },
    handleRemove () {
      this.isUpload = false
    },
    getDetail () {
      this.pageLoading = true
      categoryDetail(this.datas.id).then(res => {
        if (res) {
          if (Number(res.code) === 1) {
            this.datas = res.obj
            if (res.obj.path) {
              this.fileList.push({ url: res.obj.path })
              this.isUpload = true
            }
            this.$nextTick(() => {
              this.isUpdate = false
            })
          } else {
            this.$alert(res.code)
          }
          this.pageLoading = false
        }
      }).catch(() => {
        this.pageLoading = false
      })
    },
    goBack () {
      if (this.isUpdate) {
        this.$confirm('确定离开此页面？如果离开，更改将丢失', '提示', {
          confirmButtonText: '确定',
          cancelButtonText: '取消',
          type: 'warning'
        }).then(() => {
          this.$router.push({ name: 'Categoryindex', params: { keep: true } })
        })
      } else {
        this.$router.push({ name: 'Categoryindex', params: { keep: true } })
      }
    },
    onCheck () {
      this.$refs.dataForm.validate((valid) => {
        if (valid) {
          this.onSubmit()
        }
      })
    },
    onSubmit () {
      for (var i = 0; i < 4 - Number(this.level); i++) {
        const childSelectId = sessionStorage.getItem('select' + Number(this.level + i))
        if (childSelectId) {
          sessionStorage.removeItem('select' + Number(this.level + i))
        }
      }
      this.submitting = true
      categoryUpdate(this.datas).then(res => {
        if (res) {
          if (Number(res.code) === 1) {
            sessionStorage.setItem('select' + this.level, this.datas.id)
            this.$alert('成功', {
              confirmButtonText: '确定',
              callback: action => {
                this.$router.push({ name: 'Categoryindex', params: { keep: true } })
              }
            })
          } else {
            this.$alert(res.code)
          }
          this.submitting = false
        }
      }).catch(() => {
        this.submitting = false
      })
    }
  }
}
</script>

<style rel="stylesheet/scss" lang="scss" scoped>
.footer {
  width: 100%;
  margin: 0;
}
/deep/ .el-upload--picture-card {
  width: 88px;
  height: 88px;
  line-height: 88px;
  background: transparent;
}
/deep/ .el-upload-list--picture-card .el-upload-list__item {
  width: 88px;
  height: 88px;
  line-height: 88px;
  background: transparent;
}
/deep/ .el-upload-list__item.is-success .el-upload-list__item-status-label{
  display: none;
}
.hideUpload /deep/ .el-upload{
  display:none;   /* 上传按钮隐藏 */
}
</style>
